package com.example.fun.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.fun.R;
import com.example.fun.activity.Application;
import com.example.fun.activity.WebViewActivity;
import com.example.fun.adapter.HomeAdapter;
import com.example.fun.bean.BannerBean;
import com.example.fun.bean.InfoBean;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";
    private RecyclerView rvHome;
    private List<InfoBean.DataDTO.DatasDTO> infoBeanList = new ArrayList<>();
    private List<BannerBean.DataDTO> imageList;
    private HomeAdapter homeAdapter;
    private Banner banner;
    private int currentPosition;
    private static PersistentCookieJar cookieJar;

    public static Fragment newInstance() {
        return new HomeFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        rvHome = view.findViewById(R.id.rv_home);
        banner = (Banner) view.findViewById(R.id.banner);
        initRvHome();
        getBanner();
        initData();
        ItemClick();

        return view;
    }

    private void initData() {
        String address = "https://www.wanandroid.com/article/list/0/json";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: 当前线程：" + Thread.currentThread().getName() + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "onResponse: 当前线程：" + Thread.currentThread().getName());
                String content = response.body().string();
                Gson gson = new Gson();
                InfoBean infoBean = gson.fromJson(content, InfoBean.class);
                infoBeanList.addAll(infoBean.getData().getDatas());
                //使用Activity提供的runOnUiThread()方法切换线程
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        homeAdapter.setList(infoBeanList);
                    }
                });
            }
        });
    }


    private void initRvHome() {
        rvHome.setLayoutManager(new LinearLayoutManager(getActivity()));
        homeAdapter = new HomeAdapter(infoBeanList, getActivity());
        rvHome.setAdapter(homeAdapter);

    }

    private void ItemClick() {
        homeAdapter.setOnItemClickListener(new HomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                List<InfoBean.DataDTO.DatasDTO> list = homeAdapter.getList();
                WebViewActivity.gotoWebView(getActivity(), list.get(position).getLink());
            }
        });

        homeAdapter.setOnCollectListener(new HomeAdapter.OnCollectListener() {
            @Override
            public void onCollectClick(View view, int position) {
                currentPosition = position;
                getCollect(position);
            }
        });
    }

    private void getBanner() {
        imageList = new ArrayList<>();
        imageList.add(new BannerBean.DataDTO("https://www.wanandroid.com/blogimgs/42da12d8-de56-4439-b40c-eab66c227a4b.png", "我们支持订阅啦"));
        imageList.add(new BannerBean.DataDTO("https://www.wanandroid.com/blogimgs/62c1bd68-b5f3-4a3c-a649-7ca8c7dfabe6.png", "我们新增了一个常用导航Tab~"));
        imageList.add(new BannerBean.DataDTO("https://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png", "一起来做个App吧"));

        banner.setAdapter(new BannerImageAdapter<BannerBean.DataDTO>(imageList) {
                    @Override
                    public void onBindView(BannerImageHolder holder, BannerBean.DataDTO data, int position, int size) {
                        Glide.with(getActivity())
                                .load(data.getImagePath())
                                .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                                .into(holder.imageView);
                    }
                }).addBannerLifecycleObserver(this)
                .setIndicator(new CircleIndicator(getActivity()))
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(Object data, int position) {
                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("url", imageList.get(position).getUrl());
                        intent.putExtras(bundle);
                        getActivity().startActivity(intent);
                    }
                });
    }

    private void getCollect(int collectPosition) {
        String address;
        InfoBean.DataDTO.DatasDTO entity = homeAdapter.getList().get(collectPosition);
        if (entity.isCollect()) {
            address = "https://www.wanandroid.com/lg/uncollect_originId/" + entity.getId() + "/json";
        } else {
            address = "https://www.wanandroid.com/lg/collect/" + entity.getId() + "/json";
        }

        Log.d(TAG, "getCollect: address" + address);
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(getCookieJar())
                .build();
        FormBody body = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .post(body)
                .url(address)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "收藏失败，请检查网络！", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String collectBody = response.body().string();
                Gson gson = new Gson();
                InfoBean infoBean = gson.fromJson(collectBody, InfoBean.class);

                if (infoBean.getErrorCode() == 0) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            InfoBean.DataDTO.DatasDTO infoBeanList = homeAdapter.getList().get(currentPosition);
                            if (infoBeanList.isCollect()) {
                                Toast.makeText(getActivity(), "取消收藏成功！", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(getActivity(), "收藏成功！", Toast.LENGTH_LONG).show();
                            }
                            infoBeanList.setCollect(!infoBeanList.isCollect());
                            homeAdapter.notifyItemChanged(currentPosition);
                        }
                    });
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), infoBean.getErrorCode() + "", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });

    }

    //生成cookie
    public static ClearableCookieJar getCookieJar() {
        if (cookieJar == null) {
            cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(Application.instance));
        }
        return cookieJar;
    }

    //清除cookie
    public static void clearCookie() {
        if (cookieJar != null) {
            cookieJar.clear();
            cookieJar = null;
        }
    }


}
